const { query } = require("../../db/index")
const { getId, setToken } = require("../../utils/index")
const bcrypt = require("bcryptjs")
const { object } = require("joi")
module.exports = {
  async addUser(req, res) {
    try {
      const sql =
        "select id,userid,username,password,role,status,avatar from t_user where username=?"
      const results = await query(sql, req.body.username)
      if (results.length !== 0) return res.sendError("用户名已存在")
    } catch (error) {
      res.sendError(error)
    }

    const { confirmPassword, ...insertData } = req.body
    insertData.password = bcrypt.hashSync(req.body.password, 10)
    insertData.userid = getId()
    try {
      const insertSql = "insert into t_user set ?"
      const result = await query(insertSql, insertData)
      if (result.affectedRows !== 1) return res.sendError("新增用户失败，请稍后重试")
      res.sendSuccess("新增用户成功")
    } catch (error) {
      res.sendError(error)
    }
  },

  async getUserInfo(req, res) {
    try {
      const sql = "select * from user_userrole_dict where userid =?"
      const results = await query(sql, req.auth.userid)
      if (results.length !== 1) return res.sendError("获取用户信息失败！请联系管理员")
      res.sendSuccess(results[0])
    } catch (error) {
      res.sendError(error)
    }
  },
  async delUser(req, res) {
    try {
      const userids = req.query.userid.split(",")
      const sql = "delete from t_user where userid in (?)"
      const results = await query(sql, [userids])
      console.log(results)
      if (results.affectedRows === 0) return res.sendError("删除用户失败或用户不存在，请联系管理员")
      if (results.affectedRows !== userids.length)
        return res.sendError("删除部分用户失败或部分用户不存在,请联系管理员")
      res.sendSuccess("删除用户成功！")
    } catch (error) {
      res.sendError(error.sqlMessage)
    }
  },
  async resetPassword(req, res) {
    try {
      const sql = "select password from t_user where userid =?"
      const results = await query(sql, req.auth.userid)

      const oldPwdIsRight = bcrypt.compareSync(req.body.password, results[0].password)
      if (!oldPwdIsRight) return res.sendError("旧密码输入不正确")
      const newPwdIsEqualOldPwd = bcrypt.compareSync(req.body.confirmPassword, results[0].password)

      if (newPwdIsEqualOldPwd) return res.sendError("新密码不能与旧密码一样")
    } catch (error) {
      res.sendError(error)
    }

    try {
      const pwd = bcrypt.hashSync(req.body.confirmPassword, 10)
      const sql = "update t_user set password=? where userid =?"
      const results = await query(sql, [pwd, req.auth.userid])
      if (results.affectedRows === 0) return res.sendError("重置密码失败！请联系管理员")

      return res.sendSuccess("密码重置成功")
    } catch (error) {
      res.sendError(error.sqlMessage)
    }
  },
  async updateUser(req, res) {
    try {
      const sql = "select * from user_userrole_dict where userid =? or username =?"
      const results = await query(sql, [req.body.userid, req.body.username])
      if (
        results.length === 2 ||
        (results.length === 1 &&
          results[0].username === req.body.username &&
          results[0].userid === req.body.userid)
      )
        return res.sendError("用户名已存在！请重试")
      if (
        results.length === 1 &&
        results[0].username === req.body.username &&
        results[0].userid !== req.body.userid
      )
        return res.sendError("该用户不存在")
    } catch (error) {
      res.sendError(error.sqlMessage)
    }
    try {
      const sql = "update t_user  set ? where userid=?"
      const { userid, ...updateDate } = req.body
      const results = await query(sql, [updateDate, userid])
      if (results.affectedRows !== 1) return res.sendError("修改用户信息失败！请联系管理员")
      res.sendSuccess("修改用户信息成功！")
    } catch (error) {
      res.sendError(error.sqlMessage)
    }
  },
  async getUserList(req, res) {
    try {
      const { pageSize = 10, pageNum = 1, username, ...params } = req.query
      const offset = (pageNum - 1) * pageSize
      const usernameLike = username ? `%${username}%` : `%%`
      const values = [usernameLike, pageSize * 1, offset]
      const sql = `select * from user_userrole_dict where username like ? LIMIT ? offset ?`

      const results = await query(sql, values)
      const sqlTotals = "select count(*) as total from  user_userrole_dict"
      const totals = await query(sqlTotals)
      console.log(totals)
      res.sendSuccess({ data: results, total: totals[0].total })
    } catch (error) {
      res.sendError(error)
    }
  }
}
